import axios from 'axios';
import router from '@/router'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accessToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

let isRedirecting = false;
// 响应拦截器
request.interceptors.response.use(
    (response) => response.data,
    (error) => {
        if (error.response?.status === 401 && !isRedirecting) {
            isRedirecting = true;
            localStorage.removeItem('accessToken')
            sessionStorage.removeItem('accessToken');
            window.$message.error('登录状态已失效，请重新登录')
            router.replace('/login').then(() => location.reload());
        }
        return Promise.reject(error)
    }
)

export default request;